import uiautomator2 as u2


class AndroidTest(object):
    device = None  # 已连接的手机对象
    # wait_timeout = 300.0  # 链接超时时间

    def _get_pkg_name(self):
        """获取当前已打开的app包名"""
        pkg_name = self.device.app_current()
        return pkg_name

    def connection_by_wifi(self, ip):
        """通过同局域网的wifi链接手机"""
        self.device = u2.connect_wifi("ip")
        # self.device.wait_timeout = self.wait_timeout
        print(self.device.device_info)

    def connection_by_num(self, num):
        """通过usb链接手机后通过手机序列号连接手机"""
        self.device = u2.connect(num)
        # self.device.wait_timeout = self.wait_timeout
        print(self.device.device_info)

    def install_app(self, apk_url):
        """下载并安装apk"""
        print("start install %s" % apk_url)
        self.device.app_install(apk_url)
        print("end install %s" % apk_url)

    def uninstall(self):
        """卸载app"""
        # 获取当前打开的app的包名
        pkg_name = self._get_pkg_name()
        self.device.app_uninstall(pkg_name)

    def open_app(self, app_name):
        """通过app名称打开app, 点击app进入"""
        self.device(text=app_name).click()

    def open_app_by_pkg_name(self, pkg_name=""):
        """通过pkg名打开app"""
        if not pkg_name:
            pkg_name = self._get_pkg_name()
        self.device.app_start(pkg_name)

    def close_app(self, pkg_name=""):
        """关闭app"""
        if not pkg_name:
            pkg_name = self._get_pkg_name()
        self.device.app_stop(pkg_name)

    def clear_app(self, pkg_name=""):
        """清空app"""
        if not pkg_name:
            pkg_name = self._get_pkg_name()
        self.device.app_clear(pkg_name)

    def screenshot(self, img_path):
        """手机截屏"""
        self.device.screenshot(img_path)


if __name__ == "__main__":
    my_android = AndroidTest()
    sg = u"/xxxxx/PycharmProjects/douyin/pkg/taobao.apk"
    my_android.device.push(sg, "/data/")
    
    my_android.install_app(sg)
    my_android.open_app("淘宝")